﻿using System.Security.Claims;
using HY.Common;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;

namespace HY.Web
{
    /// <summary>
    /// 按钮授权验证（_ViewImports.cshtml内要引用命名空间）
    /// </summary>
    [HtmlTargetElement("button-auth")]
    public class ButtonAuthTagHelper : TagHelper
    {
        [ViewContext]
        public ViewContext ViewContext { get; set; }
        private HttpContext HttpContext => ViewContext.HttpContext;

        public string Id { get; set; }
        public string Text { get; set; }
        [HtmlAttributeName("class")]
        public string CssClass { get; set; }
        [HtmlAttributeName("url")]
        public string AuthUrl { get; set; }
        [HtmlAttributeName("type")]
        public string TagType { get; set; } = "a";
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            if (HttpContext.User.Identity.IsAuthenticated)
            {
                var claimIdentity = (ClaimsIdentity)HttpContext.User.Identity;
                string roleId = claimIdentity.FindFirst(SystemConst.CookieKey.RoleId)?.Value;
                string userName = claimIdentity.FindFirst(SystemConst.CookieKey.UserName)?.Value;
                if (GlobalClass.AuthCheck(userName, roleId, AuthUrl))
                {
                    output.TagName = TagType;
                    output.Attributes.SetAttribute("lay-event", Id);
                    output.TagMode = TagMode.StartTagAndEndTag;
                    output.Attributes.SetAttribute("id", Id);
                    output.Attributes.SetAttribute("class", CssClass);
                    output.Content.SetContent(Text);
                }
            }
        }
    }
}
